package com.wanmait.zaisousuo.filter;


import com.wanmait.zaisousuo.pojo.Userinfo;
import com.wanmait.zaisousuo.service.UserinfoService;
import com.wanmait.zaisousuo.util.CookieUtil;
import com.wanmait.zaisousuo.util.MD5Utils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = {"/web/*","/"})
public class AutoLoginFilter implements Filter {

    private UserinfoService userinfoService;

    public void destroy(){}
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException{
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpServletRequest request = (HttpServletRequest)req;

        HttpSession session = request.getSession();
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        if(userinfo!=null)
        {
            chain.doFilter(req, resp);
            return;
        }
        //读取cookie
        String email = CookieUtil.getCookieValue("email",request);
        String phone_number = CookieUtil.getCookieValue("phone_number",request);
        String userpass = CookieUtil.getCookieValue("userpass",request);

        if(email==null || phone_number==null || userpass==null)
        {
            chain.doFilter(req, resp);
            return;
        }
        else {
            //登录
            Userinfo userinfo1 = null;
            try {
                userinfo1 = userinfoService.findByEmailAndPhone(email,phone_number);
            } catch (Exception e) {
            }
            if(userinfo1!=null)
            {
                String pass = MD5Utils.mymd5(userinfo1.getPassword());
                if(userpass.equals(pass))
                {
                    session.setAttribute("userinfo",userinfo1);
                }
            }
            chain.doFilter(req, resp);
            return;
        }
    }
    public void init(FilterConfig config) throws ServletException {
        ServletContext sc = config.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null && cxt.getBean(UserinfoService.class)!= null && userinfoService == null)
            userinfoService = cxt.getBean(UserinfoService.class);
    }
}
